package com.jianbing.util;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.jianbing.controller.AccessController;
import com.jianbing.dao.MongoDBDao;
import com.jianbing.entity.WhiteIp;

/**
 * Created with IntelliJ IDEA. User: LFL Date: 2017/5/3 Time: 14:35 Description:
 */
@Component
public class IPUtil {
	private static Logger logger = Logger.getLogger(AccessController.class);

	private static List<String> whiteIPList = new ArrayList<String>();

	public static List<String> getWhiteIPList() {
		return whiteIPList;
	}

	public static void setWhiteIPList(List<String> whiteIPList) {
		IPUtil.whiteIPList = whiteIPList;
		logger.info("当前白名单IP---" + whiteIPList.toString());
	}

	static {
		List<WhiteIp> list = MongoDBDao.queryForList(TableUtil.whiteIp, WhiteIp.class, null, null, null, null, null);
		if (ColletionUtils.isNotEmpty(list)) {
			for (WhiteIp whiteIp : list) {
				whiteIPList.add(whiteIp.getIpAddress());
			}
		}
		logger.info("当前白名单IP---" + whiteIPList.toString());
	}

	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
	}

	public static String getIpAddr() throws UnknownHostException {
		String localIP = "";
		InetAddress addr = (InetAddress) InetAddress.getLocalHost();
		// 获取本机IP
		localIP = addr.getHostAddress().toString();
		return localIP;
	}

	public static boolean checkIp(String Ip) {
		if (whiteIPList.contains(Ip)) {
			return true;
		}
		return false;
	}

	public static boolean checkIp(HttpServletRequest request) {
		String accessIp = getIpAddr(request);
		return checkIp(accessIp);
	}

}
